import { app } from 'electron';
import { readFileSync, existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 在ES模块中获取__dirname的等效方式
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 环境检测
export const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged;

// 读取环境变量配置
export function loadEnvConfig() {
  const envConfig = {};
  
  try {
    // 优先读取生产环境配置
    const prodEnvPath = path.join(__dirname, '../../env.production');
    if (existsSync(prodEnvPath)) {
      const envContent = readFileSync(prodEnvPath, 'utf8');
      parseEnvContent(envContent, envConfig);
    }
    
    // 如果是开发环境，也读取开发环境配置
    if (isDev) {
      const devEnvPath = path.join(__dirname, '../../env.development');
      if (existsSync(devEnvPath)) {
        const envContent = readFileSync(devEnvPath, 'utf8');
        parseEnvContent(envContent, envConfig);
      }
    }
  } catch (error) {
    console.error('Failed to load environment variables:', error);
  }
  
  return envConfig;
}

// 解析环境变量内容的辅助函数
function parseEnvContent(envContent, envConfig) {
  const envLines = envContent.split('\n');
  
  envLines.forEach(line => {
    // 跳过注释和空行
    if (line.trim() && !line.trim().startsWith('#')) {
      const [key, ...valueParts] = line.split('=');
      if (key && valueParts.length > 0) {
        const value = valueParts.join('=').trim();
        // 移除引号
        envConfig[key.trim()] = value.replace(/^['"]|['"]$/g, '');
      }
    }
  });
}

// 加载环境配置
export const envConfig = loadEnvConfig();
export const ENABLE_DEBUG_CONSOLE = envConfig.VITE_ENABLE_DEBUG_CONSOLE === 'true';
export const API_BASE_URL = envConfig.VITE_API_BASE_URL || 'http://127.0.0.1:8080';